package com.linzm.leetcode.primary.数组.移除元素;

import org.junit.Test;

/**
 * @Author zimingl
 * @Date 2022/10/6 15:59
 * @Description: TODO
 */
public class 数组283移动零 {

    /**
     * 快慢指针
     *
     * @param nums
     */
    public static void moveZeroes(int[] nums) {
        int slowIndex = 0;
        int count = 0;
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
            if (nums[fastIndex] != 0) {
                nums[slowIndex] = nums[fastIndex];
                slowIndex++;
            }
            if (nums[fastIndex] == 0) {
                count++;
            }
        }
        int len = nums.length - 1;
        while ((count--) > 0) {
            nums[len--] = 0;
        }
    }

    @Test
    public void test() {
        int[] nums = new int[]{0, 1, 0, 3, 12};
        moveZeroes(nums);
    }

    public void moveZeroes2(int[] nums) {
        int left = 0, right = 0;
        while (right < nums.length) {
            if (nums[right] != 0) {
                swap(nums, left, right);
                left++;
            }
            right++;
        }
        for (right = 0; right < nums.length; right++) {
            if (nums[right] != 0) {
                swap(nums, left, right);
                left++;
            }
        }
    }

    public void swap(int[] nums, int left, int right) {
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }

    @Test
    public void test02() {
        int[] nums = new int[]{0, 1, 0, 3, 12};
        moveZeroes2(nums);
    }


}
